package com.xbongbong.paas.help;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserDepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserDepartmentModel;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @description: 用户和部门help类
 * @Author: hongxiao
 * @date: 2019-08-09 16:19
 * @since v1.0
 */
@Component
@Slf4j
public class UserAndDepartmentHelp {
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserDepartmentModel userDepartmentModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 获取公司所有的员工
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:29
     * @since v1.0
     * @version v1.0
     */
    public List<UserEntity> getAllUserList(String corpid) {

        // 从缓存获取
        String redisUserList = paasRedisHelper.getValue(RedisPrefixConstant.ALL_USER_LIST, corpid);
        List<UserEntity> allList = JsonHelperUtil.parseArray(redisUserList, UserEntity.class);
        if(Objects.nonNull(allList) && !allList.isEmpty()) {
            return allList;
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        allList = userModel.findEntitys(param);

        // 置入缓存
        paasRedisHelper.setValue(RedisPrefixConstant.ALL_USER_LIST, corpid, allList, TimeConstant.SECONDS_EIGHT_HOUR);
        return allList;
    }

    /**
     * 获取公司所有的部门
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:30
     * @since v1.0
     * @version v1.0
     */
    public List<DepartmentEntity> getAllDepartmentList(String corpid) {
        // 从缓存获取
        String redisDepartmentList = paasRedisHelper.getValue(RedisPrefixConstant.ALL_DEPARTMENT_LIST, corpid);
        List<DepartmentEntity> allList = JsonHelperUtil.parseArray(redisDepartmentList, DepartmentEntity.class);
        if(Objects.nonNull(allList) && !allList.isEmpty()) {
            return allList;
        }

        try {
            allList = departmentModel.findAllDepartment(corpid, false);
        } catch (Exception e) {
            log.error("UserAndDepartmentHelp.getAllDepartmentList", e);
        }

        // 置入缓存
        paasRedisHelper.setValue(RedisPrefixConstant.ALL_DEPARTMENT_LIST, corpid, allList, TimeConstant.SECONDS_EIGHT_HOUR);
        return allList;
    }

    public List<UserDepartmentEntity> getAllUserDepartmentList(String corpid) {
        // 从缓存获取
        String redisDepartmentList = paasRedisHelper.getValue(RedisPrefixConstant.ALL_USER_DEPARTMENT_LIST, corpid);
        List<UserDepartmentEntity> allList = JsonHelperUtil.parseArray(redisDepartmentList, UserDepartmentEntity.class);
        if(Objects.nonNull(allList) && !allList.isEmpty()) {
            return allList;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        allList = userDepartmentModel.findEntitys(param);

        // 置入缓存
        paasRedisHelper.setValue(RedisPrefixConstant.ALL_USER_DEPARTMENT_LIST, corpid, allList, TimeConstant.SECONDS_EIGHT_HOUR);
        return allList;
    }


    /**
     * 删除公司所有员工缓存
     * @param corpid
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:30
     * @since
     * @version
     */
    public void removeRedisForUser(String corpid) {
        paasRedisHelper.removeValue(RedisPrefixConstant.ALL_USER_LIST, corpid);
    }

    /**
     * 删除公司所有部门缓存
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:31
     * @since v1.0
     * @version v1.0
     */
    public void removeRedisForDepartment(String corpid) {
        paasRedisHelper.removeValue(RedisPrefixConstant.ALL_DEPARTMENT_LIST, corpid);
    }

    /**
     * 删除公司所有员工部门缓存
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-12 10:29
     * @since v1.0
     * @version v1.0
     */
    public void removeRedisForUserDepartment(String corpid) {
        paasRedisHelper.removeValue(RedisPrefixConstant.ALL_USER_DEPARTMENT_LIST, corpid);
    }

    /**
     * 获取角色对应的员工ids
     * @param corpid 公司id
     * @return {roleId1:[userId1,userId2],roleId2:[userId1,userId2]}
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:45
     * @since v1.0
     * @version v1.0
     */
    public Map<Integer, List<String>> userIdsForRole(String corpid) {
        List<UserEntity> list = getAllUserList(corpid);
        Map<Integer, List<String>> userIdsForRole = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        for(UserEntity user : list) {
            String roleIds = user.getRoleIds();
            String[] roleArray = roleIds.split("\\|");
            for (String roleIdStr : roleArray) {
                Integer roleId = StringUtil.toInt(roleIdStr, -1);
                if (userIdsForRole.containsKey(roleId)) {
                    userIdsForRole.get(roleId).add(user.getUserId());
                } else {
                    List<String> ids = new ArrayList<>();
                    ids.add(user.getUserId());
                    userIdsForRole.put(roleId, ids);
                }
            }
        }

        return userIdsForRole;
    }

    /**
     * 获取角色对应的员工ids
     * @param corpid 公司id
     * @return {roleId1:[user1,user2],roleId2:[user1,user2]}
     * @throws
     * @author hongxiao
     * @date 2019-08-09 19:47
     * @since
     * @version
     */
    public Map<Integer, List<UserEntity>> userListForRole(String corpid) {
        List<UserEntity> list = getAllUserList(corpid);
        Map<Integer, List<UserEntity>> userIdsForRole = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        for(UserEntity user : list) {
            String roleIds = user.getRoleIds();
            String[] roleArray = roleIds.split("\\|");
            for (String roleIdStr : roleArray) {
                Integer roleId = StringUtil.toInt(roleIdStr, -1);
                if (userIdsForRole.containsKey(roleId)) {
                    userIdsForRole.get(roleId).add(user);
                } else {
                    List<UserEntity> userList = new ArrayList<>();
                    userList.add(user);
                    userIdsForRole.put(roleId, userList);
                }
            }
        }

        return userIdsForRole;
    }

    /**
     * 获取deptIds对应的部门
     *
     * @param corpid 公司id
     * @param depIds 部门ids
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-12 10:05
     * @since v1.0
     * @version v1.0
     */
    public List<DepartmentEntity> getDepListByIds(String corpid, Set<Long> depIds) {
        List<DepartmentEntity> list = getAllDepartmentList(corpid);
        if(Objects.isNull(depIds) || depIds.isEmpty()) {
            return new ArrayList<>();
        }

        List<DepartmentEntity> resultList = new ArrayList<>();
        for(DepartmentEntity departmentEntity : list) {
            if(depIds.contains(departmentEntity.getId())) {
                resultList.add(departmentEntity);
            }
        }
        return resultList;
    }

    /**
     *
     * @param corpid 公司id
     * @param depIds 部门ids
     * @param isLeader 是否为主管，默认为非主管（0非主管，1主管）
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-12 10:36
     * @since v1.0
     * @version v1.0
     */
    public List<UserDepartmentEntity> getUserDepListByDepIds(String corpid, Set<Long> depIds, Integer isLeader) {
        List<UserDepartmentEntity> list = getAllUserDepartmentList(corpid);
        if(Objects.isNull(depIds) || depIds.isEmpty()) {
            return new ArrayList<>();
        }
        isLeader = isLeader == null ? Integer.valueOf(0) : isLeader;

        List<UserDepartmentEntity> resultList = new ArrayList<>();
        for(UserDepartmentEntity entity : list) {
            if(depIds.contains(entity.getDepartmentId()) && Objects.equals(entity.getIsLeader(), isLeader)) {
                resultList.add(entity);
            }
        }
        return resultList;
    }

    /**
     * 获取超管或老板
     *
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-26 20:37
     * @since v1.0
     * @version v1.0
     */
    public List<UserEntity> getAdminOrBoss(String corpid) {
        List<UserEntity> list = getAllUserList(corpid);

        List<UserEntity> resultList = new ArrayList<>();
        for(UserEntity userEntity : list) {
            if(userEntity.getRoleIds().contains(RoleEnum.ADMIN.getAlias()) || userEntity.getRoleIds().contains(RoleEnum.BOSS.getAlias())) {
                resultList.add(userEntity);
            }
        }
        return resultList;
    }
}
